package com.iyoudoock.citymine.activity.user;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.iyoudoock.citymine.BaseActivity;
import com.iyoudoock.citymine.R;
import com.iyoudoock.citymine.activity.MapActivity;
import com.iyoudoock.citymine.adapter.RecycleChoiceAdapter;
import com.iyoudoock.citymine.constants.Choice;
import com.iyoudoock.citymine.constants.HttpUtils;
import com.iyoudoock.citymine.constants.Key;
import com.iyoudoock.citymine.constants.Value;
import com.iyoudoock.citymine.utils.TransformUtils;
import com.iyoudoock.citymine.widget.wheel.WheelView;
import com.kvin.toolkit.utils.JumpUtils;
import com.kvin.toolkit.utils.MetricsUtils;
import com.kvin.toolkit.utils.PopupUtils;
import com.kvin.toolkit.utils.ToastUtils;
import com.kvin.toolkit.utils.http.JsonHttpResponseHandler;
import com.kvin.toolkit.utils.http.JsonUtils;
import com.kvin.toolkit.widget.CountDownView;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;

public class RegisterActivity extends BaseActivity {

    @BindView(R.id.phone_et)
    EditText phoneEt;
    @BindView(R.id.verify_code_btn)
    CountDownView verifyCodeBtn;
    @BindView(R.id.verify_code_et)
    EditText verifyCodeEt;
    @BindView(R.id.identity_tv)
    TextView identityTv;
    @BindView(R.id.identity_choice_container)
    LinearLayout identityChoiceContainer;
    @BindView(R.id.pwd_et)
    EditText pwdEt;
    @BindView(R.id.pwd_container)
    LinearLayout pwdContainer;
    @BindView(R.id.line_fir_view)
    View lineFirView;
    @BindView(R.id.confirm_pwd_et)
    EditText confirmPwdEt;
    @BindView(R.id.confirm_container)
    LinearLayout confirmContainer;
    @BindView(R.id.line_sec_view)
    View lineSecView;
    @BindView(R.id.ly_content)
    LinearLayout lyContent;
    @BindView(R.id.next_btn)
    Button nextBtn;
    @BindView(R.id.register_agreement_tv)
    TextView registerAgreementTv;
    @BindView(R.id.ly_identity_content)
    LinearLayout lyIdentityContent;

    private PopupUtils mPop;
    private WheelView mWheelView;

    private int currentItem = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        ButterKnife.bind(this);

    }

    @Override
    public void init() {
        mJsonUtils = JsonUtils.getInstance();
        initPop();

        identityChoiceContainer.setOnClickListener(this);
        verifyCodeBtn.setOnClickListener(this);
        nextBtn.setOnClickListener(this);
    }

    /**
     * initialize pop window of recycle choice
     */
    private void initPop() {
        View v = LayoutInflater.from(this).inflate(R.layout.pop_recycle_type, null);
        mWheelView = (WheelView) v.findViewById(R.id.recycle_type_wv);
        mWheelView.setViewAdapter(new RecycleChoiceAdapter(getActivity(), TransformUtils.generateList(Choice.recycleChoice)));
        mWheelView.setCyclic(false);
        mWheelView.setCurrentItem(0);
        mWheelView.setVisibleItems(4);

        //cancel or confirm
        v.findViewById(R.id.confirm_tv).setOnClickListener(this);
        v.findViewById(R.id.cancel_tv).setOnClickListener(this);

        //mWheelView.TEXT_SIZE = MetricsUtils.winMetrics(this).widthPixels / 20;
        mPop = PopupUtils.newInstance(v, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    }

    @Override
    public void initNav() {
        setTitle("注册");

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.identity_choice_container:
                mPop.show(identityChoiceContainer, Gravity.BOTTOM);
                break;
            case R.id.confirm_tv:
                currentItem = mWheelView.getCurrentItem();
                identityTv.setText(Choice.recycleChoice[currentItem]);
                showPswView();
                mPop.dismiss();
                break;
            case R.id.cancel_tv:
                mPop.dismiss();
                break;
            case R.id.verify_code_btn:
                verifyCodeBtn.startCount();
                getVerifyCode(phoneEt.getText().toString(), Value.VERIFY_REGISTER);
                break;
            case R.id.next_btn:
                checkVerifyCode(phoneEt.getText().toString(), verifyCodeEt.getText().toString());
                break;
        }
    }

    /**
     * register
     */
    private void register() {
        params = HttpUtils.getRegisterParams(phoneEt.getText().toString(), "A", "", "", "", "", "", "", "",
                "", pwdEt.getText().toString(), "");

        mJsonUtils.post(HttpUtils.REGISTER_URL, params, this,Value.Flag.REGISTER);
    }


    @Override
    public void onSuccess(JSONObject response, String flag) {
        super.onSuccess(response, flag);
        if (response == null) return;
        try {
            int state = response.getInt(Key.Tag.STATE);
            if (flag.equals(Value.Flag.REGISTER)) {
                if (state == Value.Response.SUCCESS) {
                    //jump to login page
                    ToastUtils.simpleToast(getActivity(), R.string.tip_register_success);
                    finish();
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onFailure(IOException e, String flag) {
        super.onFailure(e, flag);
    }

    /**
     * handle message  here
     */
    @Override
    public void onHandleMessage(Message msg) {
        super.onHandleMessage(msg);//can load default dialog
        switch (msg.what) {
            case Value.Message.VERIFY_SUCCESS:
                mPersistentUtils.writeString(Key.User.TELEPHONE, phoneEt.getText().toString());
                if (currentItem == 0) {
                    register();
                } else {
                    //jump to register recycler page
                    mIntent = new Intent(getActivity(), RegisterRecyclerActivity.class);
                    mIntent.putExtra(Key.User.ROLE_TYPE, getRoleType());
                    mIntent.putExtra(Key.User.TELEPHONE, phoneEt.getText().toString());
                    JumpUtils.simpleJump(getActivity(), null, mIntent, true);
                }
                break;
            case Value.Message.VERIFY_FAILURE:
                //toast some reason
                break;
            case Value.Response.SUCCESS:
                JumpUtils.simpleJump(getActivity(), MapActivity.class, null, true);
                break;

        }
    }

    private String getRoleType() {
        if (currentItem == 1) {
            return Value.Role.COMMUNITY;
        } else if (currentItem == 2) {
            return Value.Role.FLUENT;
        }
        return "";
    }

    /**
     * show psw views
     */
    private void showPswView() {
        if (currentItem == 0) {
            int show = View.VISIBLE;
            this.lineFirView.setVisibility(show);
            this.pwdContainer.setVisibility(show);
            this.lineSecView.setVisibility(show);
            this.confirmContainer.setVisibility(show);
        } else {
            this.lineFirView.setVisibility(View.GONE);
            this.pwdContainer.setVisibility(View.GONE);
            this.lineSecView.setVisibility(View.GONE);
            this.confirmContainer.setVisibility(View.GONE);
        }
    }
}
